import { NotFound, Forbidden } from "lin-mizar";
import Sequelize from "sequelize";
import { Task } from "../model/task";
const schedule = require("node-schedule");
class TaskDao {
  async getTask(id) {
    const task = await Task.findOne({
      where: {
        id,
      },
    });
    return task;
  }

  // async getBookByKeyword (q) {
  //   const book = await Book.findOne({
  //     where: {
  //       title: {
  //         [Sequelize.Op.like]: `%${q}%`
  //       }
  //     }
  //   });
  //   return book;
  // }

  async getTasks() {
    const tasks = await Task.findAll();

    return tasks;
  }

  async createTask(v) {
    const task = await Task.findOne({
      where: {
        name: v.get("body.name"),
      },
    });
    if (task) {
      throw new Forbidden({
        code: 10240,
      });
    }
    const tk = new Task();
    tk.name = v.get("body.name");
    tk.time = v.get("body.time");
    tk.to = v.get("body.to");
    tk.from = v.get("body.from");
    tk.info = v.get("body.info");
    await tk.save();
    return tk;
  }

  async updateTask(v, id) {
    const task = await Task.findByPk(id);
    if (!task) {
      throw new NotFound({
        code: 10022,
      });
    }
    task.name = v.get("body.name");
    task.time = v.get("body.time");
    task.to = v.get("body.to");
    task.from = v.get("body.from");
    task.info = v.get("body.info");
    await task.save();
    return task;
  }

  async deleteTask(id) {
    const task = await Task.findOne({
      where: {
        id,
      },
    });
    if (!task) {
      throw new NotFound({
        code: 10022,
      });
    }
    task.destroy();
  }
}

export { TaskDao };
